package sjtu.ist.warehouse4ws.tool.file;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadAction extends HttpServlet  {
	 private String uploadPath="c:\\Upfile\\"; // 上传文件的目录     
	    private String tempPath="c:\\upfiel"; // 临时文件目录   
	      
	    public void doGet(HttpServletRequest request, HttpServletResponse response)  
	            throws ServletException, IOException {  
	                doPost(request,response);  
	    }  
	  
	      
	    public void doPost(HttpServletRequest request, HttpServletResponse response)  
	            throws ServletException, IOException {  
	        response.setContentType("text/html;charset=UTF-8");  
	        try {     
	        	DiskFileItemFactory factory = new DiskFileItemFactory();
	        	ServletFileUpload upload = new ServletFileUpload(factory); 	        
	        	 List fileItems =upload.parseRequest(request);
	        	
	        	
	        	
//	            DiskFileUpload fu = new DiskFileUpload();  
//	            // 设置最大文件尺寸，这里是4MB      
//	            fu.setSizeMax(4194304);      
//	            // 设置缓冲区大小，这里是4KB      
//	            fu.setSizeThreshold(4096);      
//	            // 设置临时目录：      
//	            fu.setRepositoryPath(tempPath);      
//	         
//	            // 得到所有的文件：      
//	            List fileItems = fu.parseRequest(request);      
	            Iterator i = fileItems.iterator();      
	            // 依次处理每一个文件：      
	            while(i.hasNext()) {      
	                FileItem fi = (FileItem)i.next();      
	                // 获得文件名，这个文件名包括路径：      
	                String fileName = fi.getName();  
	                int start=fileName.lastIndexOf("\\");  
	                //获得上传的文件名  
	                String paths=fileName.substring(start+1, fileName.length());  
	                fi.write(new File(uploadPath+paths));     
	            }      
	            response.getWriter().write("{'success':true,'message':'文件上传成功'}");  
	        }      
	        catch(Exception e) {      
	            System.out.println(e.getMessage()+" : "+e.getCause());  
	            response.getWriter().write("{'success':false,'message':error...'}");  
	        }      
	    }  
	  
	  
	    public void init() throws ServletException {  
	            // 文件夹不存在就自动创建!  
	            if(!new File(uploadPath).isDirectory())      
	                new File(uploadPath).mkdirs();      
	            if(!new File(tempPath).isDirectory())      
	                new File(tempPath).mkdirs();    
	    }  
}
